package 题组;

/**
 * @author 挚爱之夕
 * @date 2021/9/16 - 09 - 16 - 23:02
 * @Description: 题组
 * @Version: 1.0
 */
public class _009_最大岛屿面积 {
    /**
     * 东南西北连在一起的算作一个岛屿
     * 对角线不算
     * 求最大岛屿面积
     */
    public static void main(String[] args) {
        int[][] grid = new int[][]{
                {0, 0, 1, 0, 0},
                {0, 1, 0, 1, 0},
                {0, 0, 1, 0, 0}
        };
        System.out.println(maxAreaOfIsland(grid));
    }
    //自己写的
    public static int maxAreaOfIsland(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    dfs(grid, i, j);
                    area = 0;
                }
            }
        }
        int res = max ;
        max = 0;
        return res;
    }
    static int area = 0;
    static int max = 0;
    private static void dfs(int[][] grid, int i, int j) {
        area++;
        if(area>max)
            max = area;
        grid[i][j] = 0;
        for (int k = -1; k < 2; k++) {
            for (int l = -1; l < 2; l++) {
                if (l == 0 && k == 0)
                    continue;
                if (i + k >= 0 && i + k < grid.length && j + l >= 0 && j + l < grid[0].length) {
                    if (l == 0 || k == 0) { //四个方位：东西南北
                        if (grid[i + k][j + l] == 1)
                            dfs(grid, i + k, j + l);
                    }
                }
            }
        }
    }

    //摘录
    public static int maxAreaOfIsland1(int[][] grid) {
        int max = 0;
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                if(grid[i][j] == 1){
                    max = Math.max (dfs1(grid, i, j), max);
                }
            }
        }
        return max;
    }
    static int  dfs1(int[][] grid, int i, int j){
        if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0){
            return 0;
        }
        grid[i][j] = 0;
        int count = 1;
        count += dfs1(grid, i+1, j);
        count += dfs1(grid, i-1, j);
        count += dfs1(grid, i, j+1);
        count += dfs1(grid, i, j-1);
        return count;
    }
}
